<?php /** @noinspection ALL */

/**
 * 从mongo同步商圈数据
 */

namespace app\crontab\controller\once;

use custom\Log;
use custom\Mongo;
use custom\Redis;
use map\BaiDu;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;

class BusinessArea2 extends Command {


    protected function configure() {
        $this->setName('BusinessArea2');
    }

    protected function execute(Input $input, Output $output) {
        $this->initial();
    }


    public function initial() {
        echo "runing\n";
        $mongo = Mongo::getInstance();
        $cursor = $mongo->select('ajk_business_area', ['area' => '高新'], []);
        $resss = Db::name("cs_business_area")->count();
        $total = count($cursor);
        $index = $resss + 1;
        $count = 0;
        $redisModel = Redis::getInstance();
        foreach ($cursor as $key => $value) {
            $value = (array)$value;
            $arr = $this->getAddressInfoByMap($value['name'], $value['city']);
            $city = $this->getRegionCode($value['city'], $value['area']);
            $data = [
                'id'           => $index,
                'city_id'      => $city['city_id'],
                'city_ids'     => $city['city_ids'],
                'name'         => $value['name'],
                'itime'        => time(),
                'url'          => $value['source_url'],
                'house_number' => 0,
                'location'     => Db::raw("POINT('{$arr['lng']}', '{$arr['lat']}')"),
                'lng'          => $arr['lng'],
                'lat'          => $arr['lat'],
                'source_id'    => $value['_id'],
            ];
            if ($city['city_id'] && $arr['lng'] && $arr['lat']) {
                $res[] = $data;
                $redisModel->hset('write_business', $value['name'] . '-' . $city['city_id'], $index);//商圈 映射 自增ID
                $index++;
            }


        }
        $res = $res ?? [];
        $redisModel->hset('h_write_business_result', 'write_business', serialize($res));
        $res = array_chunk($res, 500);
        foreach ($res as $k => $v) {
            Db::name("cs_business_area")->insertAll($v);
        }
        $redisModel->del('err_business');
        $suc = $index - 1;
        echo "end\n";
        echo "total:" . $total . "\n";
        echo 'success:' . $suc . "\n";
        Log::write("total->$total;success->$suc", "businessArea2.log");
    }


    /**
     * 百度-获取详细信息
     * @param $address
     * @param string $city
     * @return array
     * @throws Exception
     */
    public function getAddressInfoByMap($address, $city = '') {
        $lat = $lng = $cityCodes = $cityCode = 0;
        $res = BaiDu::placeSearch($address, $city, '商圈');
        if (!empty($res['results'])) {
            $lng = round($res['results'][0]['location']['lng'] ?? $lng, 6);
            $lat = round($res['results'][0]['location']['lat'] ?? $lat, 6);
        }
        return [
            'lat' => $lat,
            'lng' => $lng
        ];
    }

    /**
     * 获取城市code
     * @param $city
     * @param $area
     * @return array
     */
    public function getRegionCode($city, $area) {
        $p_codes = db('region')->where("name like '{$city}%' and rank=2")->value('p_codes');
        $re = db('region')->field('city_code,p_code,p_codes')->where("name like '{$area}%' and p_codes like '{$p_codes}%'")->where('rank', 3)->find();
        if (!$re) {
            $data = array(
                'city_id'  => 0,
                'city_ids' => ''
            );
            $redisModel = Redis::getInstance();
            $is_or = $redisModel->hget('err_business', $city . '-' . $area);
            if (!$is_or) {
                $redisModel->hset('err_business', $city . '-' . $area, $area);//查不到城市code的商圈存入redis
                Log::write("未找到城市区域数据;city->{$city},area->{$area}", "businessArea2.log");
            }

        } else {
            $data = array(
                'city_id'  => $re['city_code'],
                'city_ids' => $re['p_codes'] . $re['city_code'] . ','
            );
        }
        return $data;
    }
}
